package com.haoe.controller;

import com.google.common.collect.Lists;
import com.haoe.common.CommonResult;
import com.haoe.dto.vo.OrderInfoVO;
import com.haoe.entity.Order;
import com.haoe.enums.OrderStatusEnum;
import com.haoe.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @Author: 80305082
 * @Date: 2021/3/12
 * @Description: 餐厅controller层
 */
@RestController
@Slf4j
@RequestMapping("/restaurant")
//@Transactional(rollbackFor = Exception.class)
public class RestaurantController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private CustomerController customerController;

    /**
     * 接收订单: 修改中
     *
     * @param id 订单id
     * @return 接单成功
     */
    @PostMapping("/orderId/accept")
    public CommonResult acceptOrder(@RequestParam("id") Long id) {
        // todo: 参数校验。
        //  根据餐厅id，status=3 查询是否存在当前订单,如果存在，将订单状态修改为1，否则接单异常
        List<Order> orderList = orderService.selectByOrderStatus(id, OrderStatusEnum.PAID.getCode());
        if (orderList.isEmpty()) {
            return CommonResult.failed("没有可以接收的订单");
        }
        try {
            for (Order order : orderList) {
                orderService.updateOrder(order.getId(), OrderStatusEnum.ACCEPT.getCode());
            }
        } catch (Exception e) {
            log.error("接收订单异常，异常信息：{}", e.getMessage());
            return CommonResult.failed("查询订单详情异常");
        }

        return CommonResult.success(null);
    }

    /**
     * 查询当前餐厅的所有订单（status= 1 已接单 或者 2 已送达） ：已测试
     *
     * @param id 餐厅id
     * @return 餐厅接单信息
     */
    @GetMapping("/restaurantId")
    public CommonResult<List<OrderInfoVO>> queryOrderById(@RequestParam("id") Long id) {
        List<OrderInfoVO> result = Lists.newArrayList();
        List<Integer> statusList = Lists.newArrayList(OrderStatusEnum.ACCEPT.getCode(), OrderStatusEnum.ARRIVE.getCode());
        try {
            List<Order> orderList = orderService.selectByRestaurantIdAndStatus(id, statusList);
            CommonResult<List<OrderInfoVO>> res = customerController.getOrderInfoResult(id, result, orderList);
            if (res != null) return res;
        } catch (Exception e) {
            log.error("餐厅id：{} 查询订单信息异常：{}", id, e.getMessage());
            return CommonResult.failed("查询失败");
        }
        return CommonResult.success(result);
    }

}
